import { BrowserWindow, app, shell } from 'electron';
import { readBookConfig } from './utils.js'
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
let mainWin = null;

const createMainWin = () => {
  mainWin = new BrowserWindow({
    title: 'YangShaoTool',
    width: 384,
    height: 288,
    autoHideMenuBar: true,
    icon: icon,
    skipTaskbar: true, // 隐藏从任务栏中
    webPreferences: {
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      webSecurity: false, // 禁用同源策略，允许加载 blob URL
    },
    // resizable: false, // 禁止调整窗口大小
    transparent: true, // 设置窗口透明
    frame: false // 如果想要无边框的窗口
  });
  mainWin.setMaximizable(false); // 禁止最大化
  // mainWin.webContents.openDevTools()
  // 设置窗口的初始位置
  const screenSize = require('electron').screen.getPrimaryDisplay().workAreaSize;
  // mainWin.setPosition(0, screenSize.height - mainWin.getBounds().height - 5); // 最底部
  // 右上角
  mainWin.setPosition(screenSize.width - mainWin.getBounds().width - 5, 5);
  // 保持在屏幕最上层--start
  mainWin.setAlwaysOnTop(true, "screen-saver")
  mainWin.setVisibleOnAllWorkspaces(true)
  // --end
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWin.loadFile(join(__dirname, '../renderer/index.html'))
    // console.log('path',join(__dirname, '../renderer/index.html'));
  }

  mainWin.webContents.setWindowOpenHandler((details) => {
    if (url.startsWith('https:')) shell.openExternal(url);
    return { action: 'deny' }
  })
  // 当窗口被最小化时，隐藏窗口而不是真正最小化
  mainWin.on('minimize', (event) => {
    event.preventDefault() // 阻止窗口默认的最小化行为
    mainWin.hide() // 隐藏窗口
  });

  // 当窗口的关闭按钮被点击时，隐藏窗口而不是关闭应用
  mainWin.on('close', (event) => {
    if (!mainWin.isFullScreen()) { // 如果不是全屏模式，则隐藏窗口
      event.preventDefault() // 阻止窗口的关闭
      mainWin.hide() // 隐藏窗口
    }
  });

  return mainWin;
}
function closeMainWin() {
  if (mainWin && !mainWin?.isDestroyed()) {
    mainWin?.close();
  }
  mainWin = null;
}

function openMainWin() {
  if (!mainWin || mainWin?.isDestroyed()) {
    mainWin = createMainWin();
  }
  mainWin?.show();
}

function hideMainWin() {
  mainWin.hide();
}
// 写一个show和hide切换
function showHideMainWin() {
  mainWin.isVisible() ? mainWin.hide() : mainWin.show();
}
function goHomeMainWin() {
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWin.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // 假设你想在创建窗口后立即打开设置路由
  // mainWin.webContents.on('did-finish-load', () => {
  //   mainWin.webContents.send('set-route', '/setting');
  // });
}

function minimizeMainWin() {
  mainWin.minimize();
}

function focusMainWin() {
  if (!mainWin || mainWin?.isDestroyed()) {
    mainWin = createMainWin();
  } else {
    // Focus on the main window if the user tried to open another
    if (mainWin.isMinimized()) mainWin.restore();
    if (!mainWin.isVisible()) mainWin.show();
    mainWin.focus();
  }
}

function sendEuUpdateCanAvailable(arg, update) {
  if (mainWin && !mainWin?.isDestroyed()) {
    mainWin.webContents.send('eu:update-can-available', {
      update: update,
      version: app.getVersion(),
      newVersion: arg?.version,
    });
  }
}

function fullScrreenMainWin() {
  mainWin.setFullScreen(true);
}
function exitFullScrreenMainWin() {
  mainWin.setFullScreen(false);
}
// 切换全屏
function toggleFullScreen() {
  const screenSize = require('electron').screen.getPrimaryDisplay().workAreaSize;
  if (mainWin.getBounds().width == screenSize.width) {
    setLargeWin()
  } else {
    mainWin.setFullScreen(true)
  }
}

function rememberType() {
  let Bounds = readBookConfig().userSetting.Bounds
  let nowBounds = mainWin.getBounds();
  if (Bounds && (Bounds.width != nowBounds.width || Bounds.height != nowBounds.height || Bounds.x != nowBounds.x || Bounds.y != nowBounds.y)) {
    mainWin.setSize(Bounds.width, Bounds.height);
    mainWin.setPosition(Bounds.x, Bounds.y);
  }else{
    setNormalWin()
  }
}
function getPositionAndSize() {
  const Bounds = mainWin.getBounds();
  // console.log('positionVS', Bounds);
  return Bounds;
}
function setLargeWin() {
  mainWin.setSize(1280, 720);
  // const screenSize = require('electron').screen.getPrimaryDisplay().workAreaSize;
  // mainWin.setPosition(screenSize.width / 2 - 640, screenSize.height / 2 - 360);
  mainWin.center();
}
function setNormalWin() {
  mainWin.setSize(384, 288);
  const screenSize = require('electron').screen.getPrimaryDisplay().workAreaSize;
  mainWin.setPosition(screenSize.width - mainWin.getBounds().width - 5, 5);
}

function setRecordWin() {
  mainWin.setSize(384, 40);
  const screenSize = require('electron').screen.getPrimaryDisplay().workAreaSize;
  mainWin.setPosition(screenSize.width - mainWin.getBounds().width - 5, screenSize.height - mainWin.getBounds().height - 5);
}

export {
  closeMainWin,
  createMainWin,
  focusMainWin,
  hideMainWin,
  minimizeMainWin,
  openMainWin,
  sendEuUpdateCanAvailable,
  showHideMainWin,
  goHomeMainWin,
  fullScrreenMainWin,
  exitFullScrreenMainWin,
  rememberType,
  getPositionAndSize,
  setLargeWin,
  setNormalWin,
  toggleFullScreen,
  setRecordWin
};